<template>
  <Category :disable="!isShowList"/>
  <el-card shadow="always" :body-style="{ padding: '20px' }" :style="{ marginTop: '30px' }">
    <template #header v-if="isShowList">
      <el-button 
      type="primary" 
      size="default" 
      @click="addAtr" 
      :icon="Plus"
      :disabled="!category3Id"
      >新增属性</el-button>
    </template>
    <!-- card body -->
    <el-table border stripe :data="attrList" v-if="isShowList">
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column label="属性名称" prop="attrName" width="150">
      </el-table-column>
      <el-table-column label="属性值名称列表" prop="attrValueList">

        <template #default="{row}">
          <el-tag type="primary" size="normal" effect="dark" v-for="item  in row.attrValueList" :key="item.id">
            {{item.valueName}}</el-tag>
        </template>

      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="{row}">
          <el-button type="warning" size="default" :icon="Edit" @click="editAttr(row)"></el-button>
          <el-popconfirm
            title="你确定要删除这个属性吗?"
            @confirm="deleteAttr(row.id)"
          >
            <template #reference>
              <el-button
                type="danger"
                size="default"
                :icon="Delete"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div  v-else>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="属性名">
          <el-input
            placeholder="请输入属性名"
            v-model="newAttrData.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="addAttrValue" :disabled="!newAttrData.attrName">添加属性值</el-button>
        <el-button type="default" @click="cancle">取消</el-button>
      </div>
      <el-table border :data="newAttrData.attrValueList" stripe style="margin-top: 30px">
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column label="属性值名称" prop="valueName">
          <template  v-slot="{row,$index}">
            <el-input 
            v-model="row.valueName"
             placeholder="请输入新增的属性值名称" 
             size="default"  
             v-if="row.isEdit"
             ref="editEle"
             @blur="changeToLook(row,$index)"
             @focus="saveOldValue(row)"
             ></el-input>
            <span v-else 
            @click="changeToEdit(row)"
            >{{ row.valueName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{$index}">
            <el-popconfirm
              title="你确定要删除这个属性吗?"
              @confirm="deleteAttrValue($index)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="ele-Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 30px">
        <el-button type="primary" @click="saveAttr" :disabled="!(newAttrData.attrValueList.length>0)">保存</el-button>
        <el-button type="default" @click="cancle">取消</el-button>
      </div>
    </div>
  </el-card>

</template>

<script lang="ts">
import { defineComponent } from "vue";
import { storeToRefs } from "pinia";

export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { Plus ,Edit ,Delete} from "@element-plus/icons-vue";
import {watch,ref,nextTick} from "vue"
import { ElMessage } from "element-plus";
import useAttrStore from "@/stores/attr";
import {
  requestAttrList,
  requestUpdateOrAddAttr,
  requestDeleteAttr
} from "@/api/attr"
import type  {attrListType,attrListItemType,attrValueListType} from "@/api/attr"
import cloneDeep from "lodash/cloneDeep"
const attrStore = useAttrStore()
const {category3Id,category2Id,category1Id}  = storeToRefs(attrStore)
//设置初始数据
const attrList = ref<attrListType>([])

//封装一个获取属性列表的请求函数
const getAttrList = async () => {
  const result = await requestAttrList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );

  attrList.value = result;
};
watch(category3Id,async (newValue)=>{
  if (!newValue) {
    attrList.value =[]
    return
  };
    //发送请求
    getAttrList()
},{immediate:true})

//添加平台属性逻辑
const newAttrData = ref<attrListItemType>({
  attrName: "",
  categoryId: category3Id.value as number,
  categoryLevel: 3,
  attrValueList: [],
})
const isShowList = ref(true)

const addAtr = ()=>{
  isShowList.value = false
  //每一次新增 就删除上一次的逻辑
  newAttrData.value ={
    attrName: "",
    categoryId: category3Id.value as number,
    categoryLevel: 3,
    attrValueList: []
  }
}
const cancle =()=>{
  isShowList.value = true
}
//添加属性值
const addAttrValue = ()=>{
  //创建一个值的属性
  const newAttrValue = ref({
    valueName:'',
    attrId:newAttrData.value.id,
    isEdit:true
  })
    //把新增属性值数据  添加到新的书属性中
    newAttrData.value.attrValueList.push(newAttrValue.value)

    nextTick(()=>{
    editEle.value.focus()
  })
}

//点击修改函数
const editAttr=(row:attrListItemType)=>{
    //首先切换到修改页面
  isShowList.value = false

  const cloneRew = cloneDeep(row)
  cloneRew.attrValueList.forEach((item)=>{
    item.isEdit = false;
  })
  //让修改数据页面的数据回填到当前数据
  newAttrData.value = cloneRew

}

//创造一个数据用来保存input
const editEle = ref()

//创造一个点击事件函数
const changeToEdit=(row:attrValueListType)=>{
  row.isEdit =true
  //dom跟新完成后 再操作dom
  nextTick(()=>{
    editEle.value.focus()
  })
}

let  oldAttrValueName = ""
const saveOldValue =(row:attrValueListType)=>{
  //保存旧值
  oldAttrValueName = row.valueName;
  console.log(oldAttrValueName);
  
}
//失去焦点
const changeToLook =(row: attrValueListType, $index: number)=>{
  row.isEdit =false
  //如果输入的为空
  if(!row.valueName.trim()){
    //且旧值也为空
    if(!oldAttrValueName){
      newAttrData.value.attrValueList.splice($index,1);
    }else{
      //有就旧值就给就旧值
      row.valueName = oldAttrValueName
    }
  }

  //判断是否有重复项
  let isRepeat = newAttrData.value.attrValueList.some((item)=>{
    if(item ===row){
      return 
    }
    return item.valueName === row.valueName
  })
  if(isRepeat){
    row.valueName = oldAttrValueName
  }

  //统一在失去焦点后 清空旧值
  oldAttrValueName =""
}
//确定删除某条属性值
const deleteAttrValue = ($index:number)=>{
  newAttrData.value.attrValueList.splice($index, 1);
}

//确认保存按钮
const saveAttr =async ()=>{
  //遍历所有值删除isEdit
  newAttrData.value.attrValueList.forEach((item) => {
    delete item.isEdit;
  });
  //如果为空 就不能提交
  if (newAttrData.value.attrValueList.length <= 0) {
    ElMessage.error("属性值列表不能为空");
    return;
  }
  //发送请求
  try {
    await requestUpdateOrAddAttr(newAttrData.value)
    ElMessage.success("新增或者修改成功");
    //返回属性列表视图
    isShowList.value = true;
    //重新发送请求
    getAttrList();
  } catch (error) {
    ElMessage.success("新增或者修改成功");
  }
}
//删除某天属性的回调函数
const  deleteAttr=async (id:number)=>{
  try {
      await requestDeleteAttr(id)
      ElMessage.success("删除属性成功");
      //重新发送请求
      getAttrList();
  } catch (e) {
    ElMessage.error("删除属性失败");
  }
}
</script>
